﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using COMOSOFT.Class;
using COMOSOFT.JobManagement.Dataset;
using System.IO;
using DevExpress.XtraGrid.Views.Grid;
using System.Net.Mail;
using DevExpress.XtraEditors.Controls;

namespace COMOSOFT.JobManagement.Froms
{
    public partial class FrmJobManagement : Form
    {
        #region [Init Form]
       
        int time=0;
        int JID;
        DateTime? dt;
        ClassShare cls = new ClassShare("FrmJobManagement");
        Dataset.DataSet_JobManagementTableAdapters.JobAttachMentTableAdapter adt = new Dataset.DataSet_JobManagementTableAdapters.JobAttachMentTableAdapter();
        List<string> ListAttachFile = new List<string>();
        List<string> ListEmail = new List<string>();
        List<string> Values = new List<string>();
        bool isrequester = false;
        bool isapprove = true;
        bool isJobFinished = false;
        bool isnew = true;
        string comfirm = null;
        string status = null;
        bool Allow = true;
        List<object> listTO = new List<object>();
        List<object> ListCC = new List<object>();
        DataTable dtbTo=new DataTable();
        DataTable dtbSubmiterStatus;
        USC.UscActionLog uscAL = null;        
        string Assigner,mess,title;        
        public FrmJobManagement(int _JID, bool val)
        {
            InitializeComponent();
            JID = _JID;
            this.isnew = val;
        }
        #endregion

        #region [Load Data]
        public void LoadData()
        {
            try
            {
                if (JID > 0)
                {
                    contextMenuStrip_Exception.Enabled = false;
                    this.sp_JobSubmiterMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobSubmiterMenu, JID);
                    if (dataSet_JobManagement.sp_JobSubmiterMenu.Rows.Count>0)
                    {
                        group_ActionSubmiter.Controls.Clear();
                        int JFUID = Convert.ToInt32(gridView_ActionSubmiter.GetRowCellValue(0, "JFUID"));
                        USC.UscActionLog uscAL = new USC.UscActionLog(JFUID, Convert.ToInt32(gridView_ActionSubmiter.GetRowCellValue(0, "Handler")));
                        uscAL.LoadData();
                        group_ActionSubmiter.Controls.Add(uscAL);
                        uscAL.Show();
                        uscAL.Dock = DockStyle.Fill;
                    }

                    DataTable AllowSubmit = cls.GetData("sp_JobAllowSubmit", new string[] { "@JID", "@EID" }, new object[] {JID,ClassShare.Usid });
                    sp_JobRequestTimeTableAdapter.Fill(dataSet_JobManagement.sp_JobRequestTime, JID, ClassShare.Usid);
                    if (dataSet_JobManagement.sp_JobRequestTime.Rows.Count != 0)
                        dockPanel_Requesttime.Show();
                    this.jobCarbonCopyTableAdapter.Fill(dataSet_JobManagement.JobCarbonCopy, JID, ClassShare.Usid);
                    if (dataSet_JobManagement.JobCarbonCopy.Count>0)
                        isrequester = true;
                    //Enabled Controls
                    ListAttachFile.Clear();                   
                    txt_To.Properties.ReadOnly = true;
                    txt_Subjects.Properties.ReadOnly = true;
                    txt_Content.Properties.ReadOnly = true;
                    txt_Time.Properties.ReadOnly = true;
                    bnt_Attachment.Properties.Buttons[0].Enabled = false;
                    txt_Remark.Properties.ReadOnly = true;
                    txt_comboCC.Properties.ReadOnly = true;
                    dataNavigator_ActionLog.Buttons.CustomButtons[1].Enabled = false;
                    dataNavigator_ActionLog.Buttons.CustomButtons[2].Enabled = false;
                    //Fill Data
                    this.jobAssignmentTableAdapter.Fill(this.dataSet_JobManagement.JobAssignment, JID);
                    this.sp_JobSubmiterListTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterList, JID, 1, ClassShare.Usid);
                    this.jobFollowupTableAdapter.Fill(this.dataSet_JobManagement.JobFollowup, JID);                    
                    this.jobSubmiterTableAdapter.Fill(this.dataSet_JobManagement.JobSubmiter, ClassShare.Usid);
                    this.sp_JobCCListTableAdapter.Fill(dataSet_JobManagement.sp_JobCCList, JID, 1, ClassShare.Usid);
                    //JID = Convert.ToInt32(txt_JID.EditValue);
                    txt_To.CheckAll();
                    txt_comboCC.CheckAll();
                    this.Text = txt_Subjects.Text;
                    DataTable dtb = adt.GetData(JID);
                    int numrow = dtb.Rows.Count;
                    if (numrow > 0)
                    {
                        for (int i = 0; i < numrow; i++)
                        {
                            ListAttachFile.Add(dtb.Rows[i]["Filename"].ToString());
                        }
                    }
                    this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
                    this.sp_JobCheckingTableAdapter.Fill(this.dataSet_JobManagement.sp_JobChecking, JID);
                    this.sp_JobSubmiterStatusTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterStatus, JID, ClassShare.Usid, 0);
                    this.sp_JobGetSubmiterTableAdapter.Fill(this.dataSet_JobManagement.sp_JobGetSubmiter, JID, ClassShare.Usid);
                                       
                    //Check status
                    DataTable dtbJobStatus = dataSet_JobManagement.JobAssignment;
                    dtbSubmiterStatus = dataSet_JobManagement.sp_JobSubmiterStatus;
                    DataTable dtbSubmiterList = dataSet_JobManagement.sp_JobGetSubmiter;
                    if (dtbJobStatus.Rows[0]["Status"].ToString() == " Finished" || dtbJobStatus.Rows[0]["Status"].ToString() == "  Failed")
                    {
                        isJobFinished = true;
                        dataNavigator_Job.Visible = false;
                        txt_Time.Properties.ReadOnly = true;
                        dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = false;
                    }
                    else
                    {
                        if (dtbSubmiterStatus.Rows.Count > 0)
                        {                            
                            if (dtbSubmiterStatus.Rows[0]["Assigner"].ToString() == dtbSubmiterStatus.Rows[0]["Requester"].ToString())
                            {
                                isrequester = true;
                                dataNavigator_Job.Visible = true;
                                txt_Time.Properties.ReadOnly = false;
                                contextMenuStrip_Exception.Enabled = true;
                            }
                            for (int i = 0; i < dtbSubmiterStatus.Rows.Count; i++)
                            {
                                if (dtbSubmiterStatus.Rows[i]["StatusConfirm"].ToString() == "Waiting")
                                {
                                    panel_confirm.Visible = true;
                                }
                            }
                          
                            if (isrequester == false)
                            {
                                if ((dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "" || dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Reject" || dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Recall") && (AllowSubmit.Rows.Count>0))
                                {
                                    bnt_Finish.Visible = true;
                                }
                                else
                                {
                                    if (dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Waiting")
                                        bnt_recall.Visible = true;
                                }
                            }
                            panel_Status.Enabled = false;                         
                        }
                        else
                        {
                            if (dtbSubmiterList.Rows.Count > 0)
                            {
                                if (dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Waiting" || dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Approved" || dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Failed")
                                {
                                    dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = false;
                                    Allow = false;
                                }
                                else
                                    dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = true;
                                if (dtbSubmiterList.Rows[0]["Status"].ToString() != "")
                                    panel_Status.Enabled = false;
                                if (dtbSubmiterList.Rows[0]["Status"].ToString() == "Accept")
                                {
                                    if ((dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "" || dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Reject" || dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Recall") && (AllowSubmit.Rows.Count > 0))
                                        bnt_Finish.Visible = true;
                                    else
                                    {
                                        if (dtbSubmiterList.Rows[0]["StatusConfirm"].ToString() == "Waiting")
                                            bnt_recall.Visible = true;
                                    }
                                }
                                if (dtbSubmiterList.Rows[0]["Status"].ToString() == "")
                                    dockPanel_Actionlog.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
                            }
                        }
                    }
                    DisplayAtachfiles(ListAttachFile, bnt_Attachment);                    
                    if (isJobFinished == true || isrequester == true)
                        panel_Status.Visible = false;
                }
                if (isnew == false)
                {
                    this.sp_JobImportTableAdapter.Fill(this.dataSet_JobManagement.sp_JobImport,ClassShare.Usid);
                    dockPanel_SelectJob.Show();
                }
            }
            catch
            {
                MessageBox.Show("Disconnect database!", "Disconnect...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Display Attachfiles]
        private void DisplayAtachfiles(List<string> List,ButtonEdit bnt)
        {
            try
            {
                while (bnt.Properties.Buttons.Count > 1)
                {
                    bnt.Properties.Buttons.RemoveAt(0);
                }
                foreach (string fn in List)
                {
                    //dowloadfile
                    if (!File.Exists(ClassShare.lcJobAsign+fn.ToString()))
                       cls.Dowload(ClassShare.ftpJobAssign, ClassShare.lcJobAsign, fn.ToString());
                    FileInfo finfo = new FileInfo(ClassShare.lcJobAsign+ fn);
                    Image img = null;
                    if (finfo.Extension.ToLower() == ".pdf")
                    {
                        img = imageCollection2.Images[0];
                    }
                    else if (finfo.Extension.ToLower() == ".xls")
                    {
                        img = imageCollection2.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".xlsx")
                    {
                        img = imageCollection2.Images[1];
                    }
                    else if (finfo.Extension.ToLower() == ".doc")
                    {
                        img = imageCollection2.Images[2];
                    }
                    else if (finfo.Extension.ToLower() == ".docx")
                    {
                        img = imageCollection2.Images[2];
                    }
                    else
                        img = imageCollection2.Images[3];

                    
                    DevExpress.Utils.SerializableAppearanceObject serializableAppreanceObje = new DevExpress.Utils.SerializableAppearanceObject();
                    serializableAppreanceObje.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Underline);
                    serializableAppreanceObje.ForeColor = System.Drawing.Color.Blue;
                    serializableAppreanceObje.Options.UseFont = true;
                    serializableAppreanceObje.Options.UseForeColor = true;
                    DevExpress.XtraEditors.Controls.EditorButton b = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, finfo.Name.Substring(0, finfo.Name.Length), -1, true, true, false, DevExpress.XtraEditors.ImageLocation.MiddleLeft, img, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppreanceObje, "", null, null, true);
                    if (JID < 0)
                    {
                        DevExpress.XtraEditors.Controls.EditorButton delete = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph, imageCollection2.Images[5], null);
                        delete.Tag = "delete," + fn;
                        bnt.Properties.Buttons.Insert(0, delete);
                    }
                    b.Tag = ClassShare.lcJobAsign + fn;
                    bnt.Properties.Buttons.Insert(0, b);
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Choose File Attach]
        private void bnt_Attachment_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "0")
                {
                    OpenFileDialog file = new OpenFileDialog();
                    file.Multiselect = true;
                    if (file.ShowDialog() == DialogResult.OK)
                    {                      
                        for (int i = 0; i < file.FileNames.Length; i++)
                        {                           
                            string name = Path.GetFileName(file.FileNames[i]);                           
                            cls.UploadFile(file.FileNames[i], ClassShare.ftpJobAssign);
                            ListAttachFile.Add(name);
                        }
                        DisplayAtachfiles(ListAttachFile, bnt_Attachment);
                    }                   
                }
                else
                {
                    string[] tag = e.Button.Tag.ToString().Split(new string[] { "," }, 0);
                    if (tag[0] == "delete")
                    {
                        bnt_Attachment.Properties.Buttons.RemoveAt(e.Button.Index);
                        bnt_Attachment.Properties.Buttons.RemoveAt(e.Button.Index + 1);
                        if (ListAttachFile.Count() > 0)
                        {
                            for (int i = 0; i < ListAttachFile.Count(); i++)
                            {
                                if (tag[1].ToString() == ListAttachFile[i].ToString())
                                    ListAttachFile.RemoveAt(i);
                            }
                        }
                    }
                    else
                        System.Diagnostics.Process.Start(e.Button.Tag.ToString());
                }
            }
            catch
            {
                MessageBox.Show("Not find File Attach!", "Not Find...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region[Form Load]
        private void FrmJobManagement_Load(object sender, EventArgs e)
        {            
        }
        #endregion

        #region [Update Job]

        public void AddNew()
        {           
            jobAssignmentBindingSource.AddNew();
            txt_RequestDate.EditValue = DateTime.Now;
            txt_Status.Text = "Pending";
            this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
            this.sp_JobSubmiterListTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterList, JID, 0,ClassShare.Usid);
            this.sp_JobCCListTableAdapter.Fill(dataSet_JobManagement.sp_JobCCList, JID, 0, ClassShare.Usid);
            txt_From.EditValue = Convert.ToInt64(ClassShare.Usid);
            txt_Time.EditValue = DateTime.Now;
        }
        public void UpdateJob()
        {
            try
            {
                if ((isJobFinished == false && isrequester == true) || JID < 0)
                {
                    DateTime dt = Convert.ToDateTime(txt_Time.EditValue);
                    if (dt >= DateTime.Now && txt_To.EditValue.ToString()!="")
                    {
                        jobAssignmentBindingSource.EndEdit();
                        jobAssignmentTableAdapter.Update(dataSet_JobManagement.JobAssignment);
                        dataSet_JobManagement.JobAssignment.AcceptChanges();
                        this.Text = txt_Subjects.Text;
                        DataTable dtb = dataSet_JobManagement.JobAssignment;
                        JID = Convert.ToInt32(dtb.Rows[0]["JID"]);

                        listTO = txt_To.Properties.Items.GetCheckedValues();
                        ListCC = txt_comboCC.Properties.Items.GetCheckedValues();

                        if (listTO.Count > 0)
                        {
                            foreach (var item in listTO)
                            {
                                cls.UpdateData("sp_JobSubmiterInsert", new string[] { "@JID", "@Assigner", "@EID", "@ReceDate", "@DealDate" }, new object[] { JID, ClassShare.Usid, Convert.ToInt32(item), DateTime.Now, txt_Time.EditValue });
                            }
                        }
                        if (ListCC.Count > 0)
                        {
                            foreach (var item in ListCC)
                            {
                                cls.UpdateData("sp_JobInsertCC", new string[] { "@JID", "@EID" }, new object[] { JID, Convert.ToInt32(item) });
                            }
                        }
                        if (ListAttachFile.Count > 0)
                        {
                            foreach (string att in ListAttachFile)
                            {
                                cls.UpdateData("sp_JobAttachMentUpdate", new string[] { "@JID", "@FileName", "@Type", "@Date" }, new object[] { JID, att, "document", DateTime.Now });
                            }
                        }
                        SendMailNewJob();
                        MessageBox.Show("Assign Job successfully!", "Assign Success", MessageBoxButtons.OK, MessageBoxIcon.Information);                        
                        this.Close();
                    }
                    else
                        MessageBox.Show("Due date not valid or Not choose Receiver!", "Not Assign Job", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }               
            }
            catch
            {
                MessageBox.Show("Not thing Update!!", "Update Fail", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [InitNewRow]
        private void gridView_Actionlog_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;                
                view.SetFocusedRowCellValue("JID", JID);
                view.SetFocusedRowCellValue("Handler", ClassShare.Usid);
                view.SetFocusedRowCellValue("ActionDate", DateTime.Now);
            }
            catch
            {
                MessageBox.Show("Not Init new row!", "New row fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Close dock]
        private void dockPanel_Actionlog_ClosedPanel(object sender, DevExpress.XtraBars.Docking.DockPanelEventArgs e)
        {
            bnt_showdock.Visible = true;
        }
        #endregion

        #region[show dock]
        private void bnt_showdock_Click(object sender, EventArgs e)
        {      
            dockPanel_Actionlog.Show();                      
            bnt_showdock.Visible = false;
        }
        #endregion

        #region[Action log update]
        private void gridView_Actionlog_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                if (isJobFinished == false)
                {
                    jobFallowupBindingSource.EndEdit();
                    jobFollowupTableAdapter.Update(dataSet_JobManagement.JobFollowup);
                    dataSet_JobManagement.JobFollowup.AcceptChanges();
                }
            }
            catch
            {
                MessageBox.Show("Not thing update!", "Update fail...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Hide Button]
        public void CheckButton()
        {
            dockPanel_Actionlog.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            groupControl_Action.Visible = false;
        }
        #endregion           

        #region [Send Email]
        public void SendMail()
        {
            try
            {               
                ListEmail.Clear();
                MailMessage message = new MailMessage();
                SmtpClient Client = new SmtpClient();
                Client.Host = "smtp.gmail.com";
                Client.Port = 587;
                Client.Credentials = new System.Net.NetworkCredential("comosoft.como@gmail.com", "@Como324");
                Client.EnableSsl = true;
                Client.DeliveryMethod = SmtpDeliveryMethod.Network;
                message.From = new MailAddress(ClassShare.Email);
                message.Sender = new MailAddress(ClassShare.Email);
                sp_JobGetEmailTableAdapter.Fill(dataSet_JobManagement.sp_JobGetEmail, JID);
                //check submiter
                if (isrequester == true)
                {
                    dtbTo = dataSet_JobManagement.sp_JobGetEmailSubmiter;
                    int numrow = dtbTo.Rows.Count;                      
                    for (int i=0;i< numrow; i++)
                    {                           
                        ListEmail.Add(dtbTo.Rows[i]["Email"].ToString());                                
                    }
                    dtbTo = cls.GetData("sp_JobGetEmailCC",new string[]{"@JID"},new object[]{JID});
                    for (int i = 0; i < dtbTo.Rows.Count; i++)
                    {
                        ListEmail.Add(dtbTo.Rows[i]["Email"].ToString());
                    }
                }
                else
                {
                    dtbTo = dataSet_JobManagement.sp_JobGetEmail;
                    if (dtbTo.Rows.Count > 0)
                    {
                        int numrow = dtbTo.Rows.Count - 1;
                        Assigner = dtbTo.Rows[numrow]["Assigner"].ToString();
                        ListEmail.Add(dtbTo.Rows[numrow]["Email"].ToString());
                        for (int i = numrow; i >= 0; i--)
                        {
                            if (Assigner == dtbTo.Rows[i]["EID"].ToString())
                            {
                                if (dtbTo.Rows[i]["Email"] != null && dtbTo.Rows[i]["Email"].ToString() != "")
                                    ListEmail.Add(dtbTo.Rows[i]["Email"].ToString());
                                Assigner = dtbTo.Rows[i]["Assigner"].ToString();
                            }
                        }
                    }
                }
                //-----------------------------------------------
                foreach (string item in ListEmail)
                {
                    message.To.Add(new MailAddress(item));
                }

                message.Subject = title;
                message.Body = mess +
                              " </br> Job Information: " +
                              " </br> Job Name: " + txt_Subjects.Text +
                             // " </br> Job Contetn: " + txt_Content.Text +
                              " </br> Create Date: " + txt_RequestDate.EditValue.ToString();
                message.IsBodyHtml = true;  
                Client.Send(message);                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
        #endregion

        #region[Submit or Recall]

        private void bnt_Finish_Click(object sender, EventArgs e)
        {
            try
            {
                bnt_Finish.Visible = false;
                cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { JID, ClassShare.Usid, "Waiting", "Not Comment", 2 });
                if (MessageBox.Show("Do you want send email?", "Send email", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    mess = ClassShare.Usname + " finished job!";
                    title = "Finish job";
                    SendMail();
                }
                //MessageBox.Show("congratulate, you had been finished your job!", "Finishing...", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
            }
            catch
            {
                MessageBox.Show("The Status not update", "Not Update...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void bnt_recall_Click(object sender, EventArgs e)
        {
            try
            {
                cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { JID, ClassShare.Usid, "Recall", "Not Comment", 2 });
                bnt_recall.Visible = false;
                if (MessageBox.Show("Do you want to send email to Assigner?", "Send Email...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    mess = ClassShare.Usname+ " recalled job";
                    title = "Recall Job";
                    SendMail();
                }
                LoadData();                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion      

        #region[ Update Submiter Status]
        private void bnt_statusok_Click(object sender, EventArgs e)
        {
            try
            {
                this.TopMost = false;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                if (comboBoxEdit_JobStatus.SelectedIndex == 0)
                {
                    cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { JID, ClassShare.Usid, "Accept", "", 0 });
                    if (MessageBox.Show("Do you want send email?", "Send email", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        mess = ClassShare.Usname + " accept job!";
                        title = "Accept Job";
                        SendMail();
                    }                    
                }
                else
                {                  
                    string title = txt_Subjects.Text;
                    string date = txt_RequestDate.EditValue.ToString();
                    string body = txt_Content.Text;
                    TabStatus tstt = new TabStatus(JID, title, date, body, Convert.ToDateTime(txt_Time.EditValue));
                    tstt.ShowDialog();
                }
                ClassShare.frjobview.LoadData();
                dockPanel_Actionlog.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Reject-Approval]
        private void bnt_reject_Click(object sender, EventArgs e)
        {
            try
            {
                PopUpApproveStaff popupStaff = new PopUpApproveStaff(JID,0);
                popupStaff.ShowDialog();
                this.sp_JobCheckingTableAdapter.Fill(this.dataSet_JobManagement.sp_JobChecking, JID);
                gridView_JobChecking.ExpandAllGroups();
                if (isrequester == false)
                {
                    mess = ClassShare.Usname+ " Rejected this job";
                    title = "Reject job";
                    SendMail();
                }
                panel_confirm.Visible = false;
                LoadData();
            }
            catch
            {
                MessageBox.Show("You Can't reject this job!", "Can't Reject...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bnt_approval_Click(object sender, EventArgs e)
        {
            try
            {               
                PopUpApproveStaff popupStaff = new PopUpApproveStaff(JID,1);
                popupStaff.ShowDialog();
                this.sp_JobSubmiterStatusTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterStatus, JID, ClassShare.Usid, 0);
                for (int i = 0; i < dataSet_JobManagement.sp_JobSubmiterStatus.Count; i++)
                {
                    if (dtbSubmiterStatus.Rows[i]["StatusConfirm"].ToString() != "Approved")
                    {
                        isapprove = false;
                    }
                }
                if (isapprove == true)
                {
                    if (isrequester == true)
                    {
                        cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status", "@flag" }, new object[] { JID, DateTime.Now, " Finished", 1 });
                        ClassShare.frjobview.LoadData();
                    }
                }
                if (MessageBox.Show("Do you want send email?", "Send email", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    mess = ClassShare.Usname + " Approved this job! Wish you success!";
                    title = "Approval job";
                    SendMail();
                }
                LoadData();                
                panel_confirm.Visible = false;
            }
            catch
            {
                MessageBox.Show("You Can't Approval this job!", "Can't Approval...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion         

        private void gridView_ActionSubmiter_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            GridView view=sender as GridView;
            view.ClearSelection();
            if (view.FocusedRowHandle >= 0 && !view.IsGroupRow(e.FocusedRowHandle))
            {
                if (dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled == false)
                {
                    if (isJobFinished == false && Allow==true)
                        dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = true;
                    dataNavigator_ActionLog.Buttons.CustomButtons[1].Enabled = false;
                    dataNavigator_ActionLog.Buttons.CustomButtons[2].Enabled = false;
                }
                group_ActionSubmiter.Controls.Clear();
                int JFUID = Convert.ToInt32(view.GetFocusedDataRow()["JFUID"]);
                USC.UscActionLog uscAL = new USC.UscActionLog(JFUID, Convert.ToInt32(view.GetFocusedDataRow()["Handler"]));
                uscAL.LoadData();
                group_ActionSubmiter.Controls.Add(uscAL);
                uscAL.Show();
                uscAL.Dock = DockStyle.Fill;
            }
        }

        #region[Update ActionLog]
        private void dataNavigator_ActionLog_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            gridView_ActionSubmiter.FocusedRowHandle = -1;
            switch (e.Button.Tag.ToString())
            {                    
                case "Add":
                    group_ActionSubmiter.Controls.Clear();                    
                    uscAL = new USC.UscActionLog(-1,ClassShare.Usid);                    
                    group_ActionSubmiter.Controls.Add(uscAL);
                    uscAL.LoadData();
                    uscAL.Show();
                    uscAL.Dock = DockStyle.Fill;
                    dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = false;
                    dataNavigator_ActionLog.Buttons.CustomButtons[1].Enabled = true;
                    dataNavigator_ActionLog.Buttons.CustomButtons[2].Enabled = true;                    
                    break;
                case "Save":
                    try
                    {
                        if (uscAL != null && !uscAL.IsDisposed)
                        {
                            uscAL.UpdateData(JID);
                            sp_JobSubmiterMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobSubmiterMenu, JID);
                            dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = true;
                            dataNavigator_ActionLog.Buttons.CustomButtons[1].Enabled = false;
                            dataNavigator_ActionLog.Buttons.CustomButtons[2].Enabled = false;
                            group_ActionSubmiter.Controls.Clear();
                            LoadData(); 
                        }                                         
                    }
                    catch
                    {
                        MessageBox.Show("Not thing update");
                    }
                    break;
                case "Delete":
                    group_ActionSubmiter.Controls.Clear();
                    dataNavigator_ActionLog.Buttons.CustomButtons[0].Enabled = true;
                    dataNavigator_ActionLog.Buttons.CustomButtons[1].Enabled = false;
                    dataNavigator_ActionLog.Buttons.CustomButtons[2].Enabled = false;                   
                    break;
            }
        }
        #endregion

        #region[Request Time]

        private void repositoryItemButtonEdit_Confirm_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                GridView view = gridView_RequestTime as GridView;
                if (e.Button.Tag.ToString() == "Approve")
                    comfirm = "Approved";
                else
                    comfirm = "Reject";
                dockPanel_givecomment.Show();
                txt_givecomment.Focus();
                txt_givecomment.Text = "";
                dockPanel_Requesttime.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bnt_send_Click(object sender, EventArgs e)
        {
            try
            {
            GridView view = gridView_RequestTime as GridView;
            if (comfirm == "Approved")
            {
                if (isrequester == false && Convert.ToDateTime(txt_Time.EditValue) < Convert.ToDateTime(view.GetFocusedDataRow()["RequestTime"]))
                    MessageBox.Show("Request time limit exceeded\n You need request time with job creater!", "Time limit exceeded", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    cls.UpdateData("sp_JobUpdateCreateTime", new string[] { "@JID", "@CreateDate" }, new object[] { JID, Convert.ToDateTime(view.GetFocusedDataRow()["RequestTime"])});                    
                    cls.UpdateData("sp_JobUpdateRequestTime", new string[] { "@JFUID", "@JSID", "@Status", "@Remark", "@RequestTime", "@flag" }, new object[] { Convert.ToInt32(view.GetFocusedDataRow()["JFUID"]), Convert.ToInt32(view.GetFocusedDataRow()["JSID"]), comfirm, txt_givecomment.EditValue, Convert.ToDateTime(view.GetFocusedDataRow()["RequestTime"]), 1 });
                }
            }
            else
                cls.UpdateData("sp_JobUpdateRequestTime", new string[] { "@JFUID", "@JSID", "@Status", "@Remark", "@RequestTime", "@flag" }, new object[] { Convert.ToInt32(view.GetFocusedDataRow()["JFUID"]), Convert.ToInt32(view.GetFocusedDataRow()["JSID"]), comfirm, txt_givecomment.EditValue, Convert.ToDateTime(view.GetFocusedDataRow()["RequestTime"]), 0 });
            dockPanel_givecomment.Close();
            view.DeleteRow(view.FocusedRowHandle);
            if (view.RowCount == 0)
                dockPanel_Requesttime.Close();
            LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void dockPanel_givecomment_ClosedPanel(object sender, DevExpress.XtraBars.Docking.DockPanelEventArgs e)
        {
            GridView view = gridView_RequestTime as GridView;
            if (view.RowCount != 0)
                dockPanel_Requesttime.Show();
        }
        #endregion

        private void gridView_SelectJob_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                ListAttachFile.Clear();
                GridView view = sender as GridView;
                if (!view.IsGroupRow(view.FocusedRowHandle))
                {
                    int JID = Convert.ToInt32(view.GetFocusedDataRow()["JID"]);
                    this.sp_JobSubmiterListTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterList, JID, 1, ClassShare.Usid);
                    this.sp_JobCCListTableAdapter.Fill(dataSet_JobManagement.sp_JobCCList, JID, 1, ClassShare.Usid);
                    txt_To.CheckAll();
                    txt_comboCC.CheckAll();
                    txt_Subjects.EditValue = view.GetFocusedDataRow()["Title"].ToString();
                    txt_Content.EditValue = view.GetFocusedDataRow()["Content"].ToString();
                    txt_Remark.EditValue = view.GetFocusedDataRow()["Remark"].ToString();
                    DataTable dtb = adt.GetData(JID);
                    int numrow = dtb.Rows.Count;
                    if (numrow > 0)
                    {
                        for (int i = 0; i < numrow; i++)
                        {
                            ListAttachFile.Add(dtb.Rows[i]["Filename"].ToString());
                        }
                    }
                    DisplayAtachfiles(ListAttachFile, bnt_Attachment);
                }
            }
            catch
            {
            }
        }

        private void timer_Refresh_Tick(object sender, EventArgs e)
        {
            try
            {
                time++;
                if (time == 10)
                {
                    sp_JobSubmiterMenuTableAdapter.Fill(dataSet_JobManagement.sp_JobSubmiterMenu, JID);
                    sp_JobCheckingTableAdapter.Fill(dataSet_JobManagement.sp_JobChecking, JID);
                    if (isrequester == true)
                    {
                        this.sp_JobSubmiterStatusTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterStatus, JID, ClassShare.Usid, 0);
                        dtbSubmiterStatus = dataSet_JobManagement.sp_JobSubmiterStatus;
                        panel_confirm.Visible = false;
                        for (int i = 0; i < dtbSubmiterStatus.Rows.Count; i++)
                        {
                            if (dtbSubmiterStatus.Rows[i]["StatusConfirm"].ToString() == "Waiting")
                            {
                                panel_confirm.Visible = true;
                            }
                        }
                    }
                    time = 0;
                }
            }
            catch
            {
            }
        }

        #region [SendEmailNewJob]
        public void SendMailNewJob()
        {
            try
            {
                if (MessageBox.Show("Do you want send email?", "Send email", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    isrequester = true;
                    mess = ClassShare.UserN + " sent a new job to ";
                    sp_JobGetEmailSubmiterTableAdapter.Fill(dataSet_JobManagement.sp_JobGetEmailSubmiter, JID);
                    DataTable dtemail = dataSet_JobManagement.sp_JobGetEmailSubmiter;
                    if (dtemail.Rows.Count > 0)
                        mess += dtemail.Rows[0]["FullName"].ToString();
                    for (int i = 1; i < dtemail.Rows.Count; i++)
                    {
                        mess += "," + dtemail.Rows[i]["FullName"].ToString();
                    }
                    dtemail = cls.GetData("sp_JobGetEmailCC", new string[] { "@JID" }, new object[] { JID });
                    if (dtemail.Rows.Count > 0)
                    {
                        mess += "\n And CC to ";
                        mess += dtemail.Rows[0]["FullName"].ToString();
                        for (int i = 1; i < dtemail.Rows.Count; i++)
                        {
                            mess += "," + dtemail.Rows[i]["FullName"].ToString();
                        }
                    }
                    title = "New Job";
                    SendMail();
                }
            }
            catch
            { 
            }
        }
        #endregion

        #region [UpdateTime-CheckRequestTime]
        private void dataNavigator_Job_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Update")
                {
                    jobAssignmentBindingSource.EndEdit();
                    jobAssignmentTableAdapter.Update(dataSet_JobManagement.JobAssignment);
                    dataSet_JobManagement.JobAssignment.AcceptChanges();
                }
                else
                {
                    if (e.Button.Tag.ToString() == "CheckRequestTime")
                    {
                        sp_JobRequestTimeTableAdapter.Fill(dataSet_JobManagement.sp_JobRequestTime, JID, ClassShare.Usid);
                        if (dataSet_JobManagement.sp_JobRequestTime.Rows.Count != 0)
                            dockPanel_Requesttime.Show();
                    }
                    else
                       jobAssignmentTableAdapter.Fill(dataSet_JobManagement.JobAssignment, JID);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Hot Approve]
        private void bntHotApprove_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_HotApprove as GridView;
                int[] item = view.GetSelectedRows();
                foreach (int i in item)
                {
                    cls.UpdateData("sp_JobSubmiterUpdate", new string[] { "@JID", "@EID", "@Status", "@Comment", "@flag" }, new object[] { JID, Convert.ToInt32(view.GetDataRow(i)["EID"]), "Approved", "", 2 });
                }
                dockPanel_HotApprove.Close();
                try
                {
                    this.sp_JobSubmiterStatusTableAdapter.Fill(this.dataSet_JobManagement.sp_JobSubmiterStatus, JID, ClassShare.Usid, 0);
                    for (int i = 0; i < dataSet_JobManagement.sp_JobSubmiterStatus.Count; i++)
                    {
                        if (dtbSubmiterStatus.Rows[i]["StatusConfirm"].ToString() != "Approved")
                        {
                            isapprove = false;
                        }
                    }
                    if (isapprove == true)
                    {
                        if (isrequester == true)
                        {
                            cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status", "@flag" }, new object[] { JID, DateTime.Now, " Finished", 1 });
                        }
                    }
                    if (MessageBox.Show("Do you want send email?", "Send email", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        mess = ClassShare.Usname + " Approved this job! Wish you success!";
                        title = "Approval job";
                        SendMail();
                    }
                    LoadData();
                    ClassShare.frjobview.LoadData();
                    panel_confirm.Visible = false;
                }
                catch
                {
                    MessageBox.Show("You Can't Approval this job!", "Can't Approval...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                MessageBox.Show("Can't Approve");
            }
        }

        #endregion

        private void hotApproveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sp_JobGetSubmiterFailedTableAdapter.Fill(dataSet_JobManagement.sp_JobGetSubmiterFailed, JID);
            if (dataSet_JobManagement.sp_JobGetSubmiterFailed.Rows.Count > 0)
                dockPanel_HotApprove.Show();
        }

        private void finishJobToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cls.UpdateData("sp_JobStatusUpdate", new string[] { "@JID", "@FinishDate", "@Status", "@flag" }, new object[] { JID, DateTime.Now, " Finished", 1 });
            LoadData();
            ClassShare.frjobview.LoadData();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                jobAssignmentBindingSource.EndEdit();
                jobAssignmentTableAdapter.Update(dataSet_JobManagement.JobAssignment);
                dataSet_JobManagement.JobAssignment.AcceptChanges();

                sp_JobRequestTimeTableAdapter.Fill(dataSet_JobManagement.sp_JobRequestTime, JID, ClassShare.Usid);
                if (dataSet_JobManagement.sp_JobRequestTime.Rows.Count != 0)
                    dockPanel_Requesttime.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void closeToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}